package contextArgs

import (
	"context"
	"errors"
	"github.com/gin-gonic/gin"
)

// 定义上下文中的键
const (
	prefix         = "admin"
	UserUUID       = prefix + "/uuid"
	UserInternalId = prefix + "/user_internal_id"
	ShopId         = prefix + "/shopId"
)

var (
	tokenEmptyError   = errors.New("token为空")
	tokenInvalidError = errors.New("token无效")
)

// SetUserID 设定用户ID
func SetUserUserId(ctx context.Context, uuid string) {
	ctx.(*gin.Context).Set(UserUUID, uuid)
}

// SetUserID 设定用户ID
func SetUserInternalId(ctx context.Context, userID uint) {
	ctx.(*gin.Context).Set(UserInternalId, userID)
}

func SetShopId(ctx context.Context, shopId uint) {
	ctx.(*gin.Context).Set(ShopId, shopId)
}

func GetUserUserId(ctx context.Context) (userId string, err error) {
	value, exist := ctx.(*gin.Context).Get(UserUUID)
	if !exist {
		return "", tokenEmptyError
	}
	userId, ok := value.(string)
	if !ok {
		return "", tokenInvalidError
	}

	if userId == "" {
		return "", tokenEmptyError
	}

	return userId, nil
}

func GetUserInternalId(ctx context.Context) (uint, error) {
	value, exist := ctx.(*gin.Context).Get(UserInternalId)
	if !exist {
		return 0, tokenEmptyError
	}
	uuid, ok := value.(uint)
	if !ok {
		return 0, tokenInvalidError
	}

	return uuid, nil
}

func GetSHopId(ctx context.Context) (uint, error) {
	value, exist := ctx.(*gin.Context).Get(ShopId)
	if !exist {
		return 0, tokenEmptyError
	}
	shopId, ok := value.(uint)
	if !ok {
		return shopId, tokenInvalidError
	}

	return shopId, nil
}

func GetRoles(ctx context.Context, key string) ([]uint, error) {
	value, exist := ctx.(*gin.Context).Get(key)
	if !exist {
		return nil, tokenEmptyError
	}

	roles, ok := value.([]uint)
	if !ok {
		return nil, tokenInvalidError
	}
	return roles, nil
}
